<template>
  <!-- 移动端 -->

  <div class="rightMobel">
    <div class="innerBox">
      <van-field
        v-model="entityClassificationNameMobile"
        is-link
        readonly
        label-width="40"
        label="分类"
        placeholder="选择分类"
        @click="show = true"
      >
      </van-field>
      <van-popup v-model="show" round position="bottom">
        <van-cascader
          title="请选择试题分类"
          :options="treeData"
          :field-names="defaultProps"
          @close="show = false"
          @finish="onFinish"
          @change="change"
        >
          <template slot="title">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
                flex: 1;
              "
            >
              取最后选中的为筛选项
              <van-button
                type="info"
                size="mini"
                style="margin-left: 15px"
                @click="getTableData(), (show = false)"
                >选择完成</van-button
              >
            </div>
          </template></van-cascader
        >
      </van-popup>

      <div class="list">
        <div class="tableTitle">
          <span class="tableTitleKey">题型总数：</span>
          <span class="tableTitleValue">{{ total }}</span>
          <span class="tableTitleKey">题库中总题数：</span>
          <span class="tableTitleValue">{{ totalQuantity }}</span>
          <van-button type="info" size="mini" @click="screenShow = true"
            >筛选项</van-button
          >
        </div>
        <van-collapse v-model="activeNames" accordion>
          <!-- <van-collapse v-model="activeNames" accordion @change="zkCollapse"> -->
          <van-collapse-item
            v-for="(item, index) in tableData"
            :name="item.itemBankId"
            :key="item.itemBankId"
            class="listItem"
          >
            <template #title>
              <div @click="zkCollapse(item)">
                <div class="testItemContent">
                  <span v-html="setContent(item.testItemContent)"></span>
                </div>
                <div class="questionTypes">
                  <span>题型:</span><span>{{ item.questionTypes }}</span>
                </div>
                <div class="updateBy">
                  <span>创建人:</span><span>{{ item.updateBy }}</span>
                </div>
                <div class="itemBankQuestionTypeList">
                  <span>标签:</span>
                  <div>
                    <van-tag
                      v-for="(
                        label, innerIndex
                      ) in item.itemBankQuestionTypeList"
                      plain
                      type="primary"
                      :key="innerIndex"
                      >{{ label.questionTypes }}</van-tag
                    >
                  </div>
                </div>
              </div>
            </template>
            <div class="expandBox">
              <div
                class="expandLeft"
                v-if="
                  item.questionTypes != '应用题' &&
                  item.questionTypes != '填空题'
                "
              >
                <div class="left">
                  <div class="wz"><span></span>选项</div>
                </div>
                <div class="right" v-if="item.questionTypes != '判断题'">
                  <!-- <div class="RTop" v-html="item.testItemContent"></div> -->
                  <div class="rBottom">
                    <div
                      class="rItem"
                      id="option"
                      v-for="item in item.answerList"
                    >
                      <span>{{ item.identifier }}、</span>
                      <span v-html="item.answerContent"></span>
                    </div>
                  </div>
                </div>
                <div class="right" v-else>
                  <!-- <div class="RTop" v-html="item.testItemContent"></div> -->
                  <div class="rBottom">
                    <el-radio label="正确"></el-radio>
                    <el-radio label="错误" style="margin-left: 15px"></el-radio>
                  </div>
                </div>
              </div>
              <div class="expandRight">
                <div class="eItem">
                  <div class="wz"><span></span>答案</div>
                  <div class="eRItem">{{ item.answerJ.join(",") }}</div>
                </div>
                <div
                  class="eItem"
                  style="flex-direction: column; align-items: flex-start"
                >
                  <div class="wz"><span></span>解析</div>
                  <div
                    class="eRItem"
                    v-html="setContent(gogo(item.analysis))"
                  ></div>
                </div>
                <div class="eItem">
                  <div class="wz"><span></span>难度</div>
                  <div class="eRItem">{{ item.difficulty }}</div>
                </div>
                <!-- <div style="display: flex;position: absolute;bottom: 40px;right: 30px;"> -->
              </div>
            </div>
          </van-collapse-item>
        </van-collapse>
      </div>
      <div class="listQueryParams">
        <pagination
          v-if="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getTableData"
          :layout="' prev, pager, next'"
        />
      </div>
    </div>

    <!-- 筛选项弹出层 -->
    <van-popup
      v-model="screenShow"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <div class="popupQuery">
        <van-form>
          <van-field
            v-model="queryParams1.questionTypesName"
            label="标签"
            placeholder="标签"
            :readonly="true"
            @click="labelPopup = true"
          />
          <van-popup v-model="labelPopup" round position="bottom">
            <van-cascader
              :options="labelTreeData"
              @close="labelPopup = false"
              :field-names="laeblDefaultProps"
              @change="labelChange"
              @finish="labelFinish"
            >
              <template slot="title">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    flex: 1;
                  "
                >
                  取最后选中的为筛选项
                  <van-button
                    type="info"
                    size="mini"
                    style="margin-left: 15px"
                    @click="labelPopup = false"
                    >选择完成</van-button
                  >
                </div>
              </template>
            </van-cascader>
          </van-popup>
          <van-field
            v-model="queryParams.difficulty"
            label="难易度"
            placeholder="难易度"
            :readonly="true"
            @click="difficultyPopup = true"
          />
          <van-popup v-model="difficultyPopup" round position="bottom">
            <van-picker
              show-toolbar
              :columns="difficultyColumns"
              @cancel="difficultyPopup = false"
              @confirm="
                (val) => {
                  (queryParams.difficulty = val), (difficultyPopup = false);
                }
              "
            />
          </van-popup>
          <van-field
            v-model="queryParams.questionTypes"
            label="题型"
            placeholder="题型"
            :readonly="true"
            @click="questionTypesPopup = true"
          />
          <van-popup v-model="questionTypesPopup" round position="bottom">
            <van-picker
              show-toolbar
              :columns="questionTypesColumns"
              @cancel="questionTypesPopup = false"
              @confirm="
                (val) => {
                  (queryParams.questionTypes = val),
                    (questionTypesPopup = false);
                }
              "
            />
          </van-popup>
          <van-field
            v-model="queryParams.testItemContent"
            label="试题内容"
            placeholder="试题内容"
          />
          <van-field
            v-model="queryParams.analysis"
            label="解析"
            placeholder="解析"
          />

          <van-field
            v-model="queryParams.createBy"
            label="创建者"
            placeholder="创建者"
          />
          <div style="margin: 16px">
            <van-button
              round
              block
              type="info"
              native-type="submit"
              @click="getTableData(), (screenShow = false)"
              >搜索</van-button
            >
          </div>
        </van-form>
      </div>
    </van-popup>
    <!-- 筛选项弹出层 -->
  </div>

  <!-- 移动端 -->
</template>
<script>
import {
  listClassification,
  getClassification,
  delClassification,
  addClassification,
  updateClassification,
  listBank,
  listAnswer,
  delBank,
} from "@/api/questionBank/management";
import { getToken } from "@/utils/auth";
import { listTypes } from "@/api/questionBank/type.js";

export default {
  components: {},

  data() {
    return {
      treeData: [],
      defaultProps: {
        text: "name",
        value: "id",
        children: "children",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        entityClassificationId: null,
        params: { questionTypesId: null },
        difficulty: null,
        questionTypes: null,
        testItemContent: null,
        analysis: null,
        createBy: null,
      },
      queryParams1: {
        questionTypesName: "",
      },
      total: 0,
      totalQuantity: 0,
      oldBankId: "",
      //移动端
      entityClassificationNameMobile: "",
      show: false,
      activeNames: [], //折叠面板
      screenShow: false,
      labelTreeData: [],
      labelPopup: false,

      laeblDefaultProps: {
        children: "children",
        text: "name",
        value: "id",
      },
      //难易度筛选项
      difficultyPopup: false,
      difficultyColumns: ["简单", "普通", "困难"],
      questionTypesPopup: false,
      questionTypesColumns: ["单选题", "多选题", "判断题", "应用题", "填空题"],
    };
  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },

  mounted() {
    this.getTreeList();
    this.getLabelTreeList();

    setTimeout(() => {
      //判断是否初始配置，若无则配置。
      if (!this.mathJax.isMathjaxConfig.bool) {
        this.mathJax.initMathjaxConfig();
      }
      this.$nextTick((_) => {
        //传入组件id，让组件被MathJax渲染
        this.mathJax.MathQueue("questionList-page");
      });
    }, 300);

    this.getTableData();
  },
  watch: {
    queryParams: {
      handler: function (n, o) {
        localStorage.setItem("params", JSON.stringify(this.queryParams));
      },
      deep: true,
    },
  },

  methods: {
    gogo(val) {
      // console.log(val);
      if (val == "" || val == null) return;
      let item = JSON.parse(JSON.stringify(val));
      let ord = /begin{array}([\s\S]*?)\\end{array}/g; // 定义正则表达式，用于匹配以 [\begin{array} 开头的字符串

      let arr = item.match(ord); // 使用 match 方法获取所有匹配项
      // console.log(arr, "arr");
      if (arr == null || arr.length == 0) return val;

      let deleP = (P) => {
        let newP = P.split("<p>");
        let a = newP.join(" ");
        let b = a.split("</p>");
        let c = b.join(" ");
        // console.log(c, "newp");
        return c;
      };

      let abc = null;
      arr.forEach((ele) => {
        abc = val.split(ele);
        abc = abc.join(deleP(ele));
      });
      return abc;
    },

    getTreeList() {
      listClassification().then((res) => {
        this.treeData = res.data;
        this.initTree(this.treeData);
      });
    },
    initTree(val) {
      for (var i = 0; i < val.length; i++) {
        if (val[i].children.length == 0) {
          delete val[i].children;
        } else {
          this.initTree(val[i].children);
        }
      }
    },

    remove(node, data) {
      delClassification(data.id).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.getTreeList();
        }
      });
    },
    getTableData() {
      listBank(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.tableData = res.rows;
          this.total = res.total;
          this.totalQuantity = res.totalQuantity;
        } else {
          this.$message.warning("搜索内容为空");
        }
      });
    },
    addQuestions() {
      this.$router.push("/questionBank/questionBank/management/addQuestions");
    },

    //修改题目
    editTable(val) {
      this.$router.push(
        "/questionBank/questionBank/management/addQuestions?itemBankId=" +
          val.itemBankId
      );
    },
    //处理标签
    setLabel(val) {
      let arr = [];
      val.forEach((ele) => {
        arr.push(ele.questionTypes);
      });
      return arr;
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.show = false;
      this.getTableData();
    },
    //选中项变化时触发
    change({ value, selectedOptions, tabIndex }) {
      console.log(value, selectedOptions, tabIndex);
      this.queryParams.entityClassificationId =
        selectedOptions[selectedOptions.length - 1].id;
      this.entityClassificationNameMobile =
        selectedOptions[selectedOptions.length - 1].name;
    },
    //展开折叠面板
    zkCollapse(row) {
      if (row.answerList && row.answerList.length != 0) return;
      let obj = {
        itemBankId: row.itemBankId,
      };
      listAnswer(obj).then((res) => {
        if (res.code == 200) {
          row.answerList = res.rows;
          //判断是否初始配置，若无则配置。
          if (!this.mathJax.isMathjaxConfig.bool) {
            this.mathJax.initMathjaxConfig();
          }
          this.$nextTick((_) => {
            //传入组件id，让组件被MathJax渲染
            this.mathJax.MathQueue("questionList-page");
          });
        }
      });
    },
    //获取标签树状图

    getLabelTreeList() {
      let arr = [
        {
          name: "题型辨识",
          type: 999,
          id: 5,
          children: [],
        },
        {
          name: "条件翻译",
          type: 999,
          id: 8,
          children: [],
        },
        {
          name: "计算",
          type: 999,
          id: 9,
          children: [],
        },
      ];

      for (let i = 0; i < arr.length; i++) {
        listTypes({ reserve3: arr[i].id }).then((Response) => {
          if (Response.code == 200) {
            arr[i].children = Response.rows;
          }
        });
      }
      console.log(arr, "4545");
      this.labelTreeData = arr;
      this.initTree(this.labelTreeData);
    },
    //标签筛选项
    labelFinish({ selectedOptions }) {
      this.labelPopup = false;
    },
    labelChange({ selectedOptions }) {
      this.queryParams1.questionTypesName =
        selectedOptions[selectedOptions.length - 1].name;

      this.queryParams.params.questionTypesId =
        selectedOptions[selectedOptions.length - 1].id;
    },

    //img去除\\
    setContent(val) {
      try {
        if (val.includes('\\\\"')) {
          let abc = val.replaceAll('\\\\"', "");
          return abc;
        } else {
          let abc = val.replaceAll('\\"', "");
          return abc;
        }
      } catch (error) {
        console.log(error);
        return val;
      }
    },
  },
};
</script>
<style scoped lang="scss">
.rightMobel {
  padding: 0;
  width: 100%;
  height: 100%;
  font-size: 12px;

  .innerBox {
    height: 100%;

    position: relative;

    .list {
      height: calc(100% - 90px);
      overflow: auto;

      // background-color: red;
      .tableTitle {
        text-align: right;
        font-size: 12px;
        padding: 5px 0;
        display: flex;
        align-items: center;
        height: 50px;
        justify-content: flex-end;

        /* .tableTitleKey {
          margin-top: 8px;
        } */
        .tableTitleValue {
          margin-right: 15px;
        }
      }

      .listItem {
        min-height: 80px;
        background-color: white;
        margin-bottom: 15px;
        padding: 10px;

        .questionTypes {
          padding-top: 8px;

          span:nth-of-type(1) {
            margin-right: 8px;
          }
        }

        .updateBy {
          padding: 8px 0;

          span:nth-of-type(1) {
            margin-right: 8px;
          }
        }

        .itemBankQuestionTypeList {
          display: flex;

          > span {
            min-width: max-content;
            margin-right: 8px;
          }

          > div {
            display: flex;
            flex-wrap: wrap;
            min-height: max-content;

            > .van-tag {
              margin: 5px 10px;
            }
          }
        }

        .expandBox {
          height: auto;
          // height: 500px;
          font-size: 12px;

          .expandLeft {
            background-color: white;
            overflow: auto;
            /* display: flex; */

            .rItem {
              margin-bottom: 15px;
              padding-left: 10px;
            }
          }

          .wz {
            min-width: 35px;
            margin-right: 15px;
            display: flex;
            align-items: center;
            margin-bottom: 15px;

            > span {
              display: inline-block;
              width: 5px;
              height: 20px;
              background-color: rgba(255, 0, 0, 0.606);
              margin-right: 5px;
              border-radius: 5px;
            }
          }

          .eRItem {
            padding-left: 10px;
            margin-bottom: 8px;
          }

          .expandLR {
            width: 20px;
          }
        }
      }
    }

    .listQueryParams {
      position: absolute;
      bottom: 0;
      right: 0;
      height: 50px;
      width: 100%;

      .pagination-container {
        background-color: rgba($color: #000000, $alpha: 0);
        margin-bottom: 20px;
        padding: 0 20px !important;
      }
    }
  }

  .popupQuery {
    height: 100%;
    width: 100%;
  }
}

::v-deep .van-cell__title {
  .testItemContent {
    min-width: fit-content;
  }
  overflow: auto;
  > div {
  }
}
</style>
